<template>
  <div class="app-container">
    <AddBtn :handleClick="handleCreate" :text="text"/>
    <el-table :data="fanganList" border style="width: 100%" v-loading="listLoading">
      <el-table-column align="center" label="ID" prop="id" width="95" type="index"></el-table-column>
      <el-table-column prop="name" label="名称" width="250"></el-table-column>
      <el-table-column prop="isPublic" label="类型">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.isPublic=== true" type="primary">公有</el-tag>
          <el-tag v-else type="warning">私有</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="300" align="center">
        <template slot-scope="scope">
          <el-button size="small" type="success" @click="handleDownload(scope.$index, scope.row)">
            <i class="el-icon-download"></i>
          </el-button>
          <el-button size="small" type="warning" @click="handleUpdate(scope.$index, scope.row)">
            <i class="el-icon-edit"></i>
          </el-button>
          <el-button type="danger" size="small" icon="el-icon-delete" @click="handleDel(scope.$index, scope.row)"></el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
      <el-form label-width="120px" :model="Form" :rules="FormRules" ref="dataForm">
        <el-form-item label="模板名称" prop="name" width="100%">
          <el-input v-model="Form.name"></el-input>
        </el-form-item>
        <el-form-item label="模板类型" prop="isPublic">
          <el-select v-model="Form.isPublic" class="filter-item" placeholder="请选择类型">
            <el-option v-for="item in TypeOptions" :key="item.value" :label="item.label" :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="布点方式" prop="did">
          <el-select v-model="Form.did" class="filter-item" placeholder="请选择布点方式">
            <el-option v-for="item in distributionOptions" :key="item.did" :label="item.distributionName" :value="item.did"/>
          </el-select>
        </el-form-item>
        <el-form-item label="方案模板："prop="fileData"  v-if='dialogStatus == "createIncubator" || dialogStatus == "createCar" || dialogStatus == "createWarehouse"'>
          <UploadFile  ref="createUploadFile" :fileName="fileName" :FileUrl="fileUploadUrl" :isMultiple="false" :isAutoUpload="false" :Data="Data" :handleChange="handleFileChange" ></UploadFile>
        </el-form-item>
         <el-form-item label="方案模板："prop="fileData" v-else >
          <UploadFile  ref="upDateUploadFile" :fileName="fileName" :FileUrl="fileUploadUrl" :isMultiple="false" :isAutoUpload="true" :Data="Data" :handleAvatarSuccess='handleAvatarSuccess'></UploadFile>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="dialogConfirm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  getFanganList,
  getFanganData,
  createFangan,
  updateFangan,
  deleteFangan
} from "@/api/fangan";
import { getDistributionList } from "@/api/distribution";
import UploadFile from "@/components/Upload/UploadFile";
import AddBtn from "@/views/layout/components/AddBtn";
import { mapGetters } from "vuex";
export default {
  name: "fanganTempDetail",
  props: {
    deviceType: {
      type: Number,
      default: 1
    }
  },
  components: { AddBtn, UploadFile },
  data() {
    return {
      text: "方案模板",
      fanganList: [],
      distributionOptions: [],
      fileUploadUrl: "http://gsp.coldcloud.com/planModel/doc/update",
      fileName: '',
      isAutoUpload:false,
      listLoading: false,
      dialogStatus: "",
      Data: {},
      textMap: {
        createIncubator: "新增保温箱方案模板",
        createCar: "新增冷藏车方案模板",
        createWarehouse: "新增库房方案模板",
        updateIncubator: "编辑保温箱方案模板",
        updateCar: "编辑冷藏车方案模板",
        updateWarehouse: "编辑库房方案模板"
      },

      TypeOptions: [{ value: true, label: "公有" }, { value: false, label: "私有" }],
      dialogFormVisible: false,
      Form: {
        name: "",
        isPublic: null,
        did: null,
      //  picData:null,
        fileData:null
      },
      FormRules: {
        name: [{ required: true, message: "请输入方案模板名称", trigger: "blur" }],
        isPublic: [{ required: true, message: "请选择类型", trigger: "change" }],
        did: [{ required: true, message: "请选择布点方式", trigger: "change" }],
        fileData: [{ required: true, message: "请上传模板文件", trigger: "change" }]
      }
    };
  },
  created() {
    this.getList();
    this.getDistributionCode();
  },
  computed: {
    ...mapGetters(["customerid"])
  },

  watch: {
    Form: {
      handler(newval, oldval) {
        this.Form.fileData = newval.fileData;
      },
      deep: true,
      immediate: true
    }
  },

  methods: {    
    // 文件上传前检查
    handleFileChange(file, fileList) {
      const isWord = file.raw.type == "application/msword" || file.raw.type == "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!isWord) {
        this.$message.error("上传文件只能是word格式!");
      }
      if (!isLt5M) {
        this.$message.error("上传文件大小不能超过5MB!");
      }
      if (isWord && isLt5M) {
        this.Form.fileData = file;
        this.fileName = file.name;
      } else {
        fileList.pop();
      }
      return isWord && isLt5M;
    },
     // 更新文件上传成功后
    handleAvatarSuccess(response, file, fileList) {
      this.$message({
        message: '更新附件上传成功',
        type: 'success'
      });
      this.dialogFormVisible = false;
      this.getList();
    },

    // 获取布点方式
    getDistributionCode() {
      getDistributionList({
        customerId: this.customerid,
        deviceType: this.deviceType
      }).then(response => {
        this.distributionOptions = response.data.map(item => {
          return { did: item.id, distributionName: item.name };
        });
      });
    },

    //获取列表
    getList() {
      this.listLoading = true;
      getFanganList({
        customerId: this.customerid,
        deviceType: this.deviceType
      })
        .then(response => {
          this.fanganList = response.data;
          this.listLoading = false;
        })
        .catch(e => {});
    },

    // 弹出框确定按钮
    dialogConfirm() {
      if ((this.dialogStatus == "createIncubator") || (this.dialogStatus == "createCar") || (this.dialogStatus == "createWarehouse")) {
        this.fanganCreate();
      } else {
        this.fanganUpdate();
      }
    },

    // 新增方案弹窗
    handleCreate() {
      this.Form = {
        name: "",
        isPublic: null,
        fileData: null
      };
      this.fileName = '';
      if (this.deviceType === 1) {
        this.dialogStatus = "createIncubator";
      } else if (this.deviceType === 2) {
        this.dialogStatus = "createCar";
      } else {
        this.dialogStatus = "createWarehouse";
      }
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs.dataForm.clearValidate();
      });
    },

    //新增方案模板
    fanganCreate() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          this.$confirm("确认提交吗？", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消"
          }).then(() => {
            let tempData = Object.assign({}, this.Form, { customerId: this.customerid }, { deviceType: this.deviceType });
            createFangan(tempData).then(res => {
              const pid = res.data.insertId;
              this.Data = { pid: pid };
              this.$nextTick(() => {
                this.$refs.createUploadFile.UploadSubmit();
              });
              this.dialogFormVisible = false;
              this.getList();
              this.$notify({
                title: "成功",
                message: "新增方案模板成功",
                type: "success",
                duration: 2000
              });
            });
          });
        }
      });
    },

    //更新弹窗
    handleUpdate(index, row) {
     if (this.deviceType === 1) {
        this.dialogStatus = "updateIncubator";
      } else if (this.deviceType === 2) {
        this.dialogStatus = "updateCar";
      } else {
        this.dialogStatus = "updateWarehouse";
      }
      getFanganData({ planModelId: row.pid }).then(res => {
        this.Form = res.data;
        this.Form.fileData = res.data.doc
        this.fileName = res.data.doc.originname;
        const pid = res.data.pid;
        this.Data = { pid: pid };
      }).catch(e=>{})
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs.dataForm.clearValidate();
      });
    },

    //编辑方案模板
    fanganUpdate() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          const tempData = Object.assign({}, this.Form);
          updateFangan(tempData).then(() => {
            this.getList();
            this.dialogFormVisible = false;
            this.$notify({
              title: "成功",
              message: "更新方案模板成功",
              type: "success",
              duration: 2000
            });
          });
        }
      });
    },

    //删除方案模板
    handleDel(index, row) {
      this.$confirm("确认删除该方案模板吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.listLoading = true;
        deleteFangan({ pid: row.pid }).then(() => {
          this.listLoading = false;
          this.$notify({
            title: "成功",
            message: "删除成功",
            type: "success",
            duration: 2000
          });
          this.getList();
        });
      }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });;
    },

    //下载
    handleDownload(index, row){
      window.open(row.doc.url);
    }
  }
};
</script>


